<?php
/**
 * @author  Eddy <cumtsjh@163.com>
 */

namespace App\Repository\Basic;

use App\Model\Basic\Category;
use App\Model\Basic\Comment;
use App\Model\Basic\CommentOperateLog;
use App\Model\Basic\ContentTag;
use App\Model\Basic\Entity;
use App\Model\Basic\EntityField;
use App\Repository\Searchable;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use App\Exceptions\CreateTableException;

class EntityRepository
{
    use Searchable;

    public static function list($perPage, $condition = [])
    {
        $data = Entity::query()
            ->where(function ($query) use ($condition) {
                Searchable::buildQuery($query, $condition);
            })
            ->orderBy('id', 'desc')
            ->paginate($perPage);
        $data->transform(function ($item) {
            xssFilter($item);
            $item->editUrl = route('admin::entity.edit', ['id' => $item->id]);
            $item->deleteUrl = route('admin::entity.delete', ['id' => $item->id]);
            $item->fieldUrl = route('admin::entityField.index') . '?entity_id=' . $item->id;
            $item->contentUrl = route('admin::content.index', ['entity' => $item->id]);
            $item->commentListUrl = route('admin::comment.index', ['entity_id' => $item->id]);
            return $item;
        });

        return [
            'code' => 0,
            'msg' => '',
            'count' => $data->total(),
            'data' => $data->items(),
        ];
    }

    /**
     * 新增模型
     *
     * @param array $data
     * @param mixed $createDB
     * @return Entity
     * @throws CreateTableException|\Exception
     */
    public static function add($data, $createDB = true)
    {
        $entity = Entity::query()->create($data);
        try {
            if (!$createDB) {
                return $entity;
            }

            if (Schema::hasTable($data['table_name'])) {
                throw new \RuntimeException("数据库表已存在");
            }

            Schema::create($data['table_name'], function (Blueprint $table) use ($entity) {
                if ($entity->type == 'document') {
                    $table->integer('id');
                } else {
                    $table->increments('id');
                }
                $table->timestamps();
                $table->engine = 'InnoDB';
            });

            return $entity;
        } catch (\Exception $e) {
            $entity->delete();
            throw new CreateTableException("创建数据库表异常");
        }
    }

    public static function update($id, $data)
    {
        return Entity::query()->where('id', $id)->update($data);
    }

    public static function find($id)
    {
        return Entity::query()->find($id);
    }

    public static function external($id)
    {
        return Entity::query()->External()->find($id);
    }

    public static function all()
    {
        return Entity::query()->get();
    }

    public static function systemMenu($type = null)
    {
        $query = Entity::query();
        if ($type) {
            $query->where('type', $type);
        }
        $entities = $query->where('is_show_content_manage', Entity::CONTENT_MANAGE_YES)
            ->get();
        $autoMenu = [];
        foreach ($entities as $k => $v) {
            $autoMenu[] = [
                'url' => route('admin::content.index', ['entity' => $v->id]),
                'name' => $v->name,
                'id' => $v->id,
                'type' => $v->type,
            ];
        }

        return $autoMenu;
    }

    public static function delete($id)
    {
        $table = Entity::query()->findOrFail($id);
        DB::beginTransaction();

        Schema::dropIfExists($table->table_name);
        Entity::destroy($id);
        EntityField::query()->where('entity_id', $id)->delete();
        Category::query()->where('model_id', $id)->delete();
        ContentTag::query()->where('entity_id', $id)->delete();
        CommentOperateLog::query()->join('comments', 'comment_operate_logs.comment_id', '=', 'comments.id')
            ->where('entity_id', $id)
            ->delete();
        Comment::query()->where('entity_id', $id)->delete();

        DB::commit();
    }

    public static function createDocumentEntityFields(Entity $entity)
    {
        $list = json_decode(file_get_contents(storage_path('doc_field.json')), true);
        foreach ($list as $key => &$value) {
            unset($value['id']);
            $value['entity_id'] = $entity->id;
        }
        EntityField::query()->insert($list);
        /* $entityId = $entity->id;
         $entityNameDefValue = $entity->entity_model_name;
         $sql  = "INSERT INTO `cms_entity_fields` (`name`, `type`, `comment`, `default_value`, `form_name`, `form_type`, `form_comment`, `form_params`, `is_show`, `is_show_inline`, `is_edit`, `is_required`, `entity_id`, `order`, `form_default_value`, `created_at`, `updated_at`, `deleted_at`) VALUES('name', 'char', '文档唯一标识 根据规则自动生成', '', '唯一标识', 'input', '文档唯一标识 根据规则自动生成', '', 1, 0, 1, 1, {$entityId}, 1, '', '2020-01-14 09:26:12', '2020-01-14 09:37:44', NULL),('lang', 'string', '语言类型', 'cn', '语言', 'option', '语言类型', 'cn=中文\nen=英文', 1, 0, 1, 1, {$entityId}, 2, 'cn', '2020-01-14 09:27:25', '2020-01-14 09:39:11', NULL),('title', 'string', '文档标题', '', '标题', 'input', '', '', 1, 0, 1, 1, {$entityId}, 3, '', '2020-01-14 09:36:52', '2020-01-14 09:36:52', NULL),('keyword', 'string', '关键字', '', '关键字', 'input', '关键字', '', 1, 0, 1, 1, {$entityId}, 4, '', '2020-01-14 09:39:55', '2020-01-14 09:39:55', NULL),('description', 'string', '简介', '', '简介', 'textArea', '', '', 1, 0, 1, 1, {$entityId}, 5, '', '2020-01-14 09:40:34', '2020-01-14 09:40:34', NULL),('category_id', 'integer', '栏目编号', '0', '栏目', 'reference_category', '', '', 1, 0, 1, 1, {$entityId}, 6, '0', '2020-01-14 09:41:26', '2020-01-14 09:41:26', NULL),('cover_image', 'string', '封面图片', '', '封面图片', 'upload', '', '', 1, 0, 1, 1, {$entityId}, 7, '', '2020-01-14 09:42:07', '2020-01-14 09:42:07', NULL),('entity_name', 'string', '', '文档类型', '{$entityNameDefValue}', 'input', '', '', 0, 0, 0, 0, {$entityId}, 8, '{$entityNameDefValue}', '2020-01-14 09:43:49', '2020-01-14 09:53:06', NULL),('click', 'integer', '点击量', '0', '点击量', 'input', '', '', 0, 0, 0, 0, {$entityId}, 9, '', '2020-01-14 09:44:26', '2020-01-14 09:53:20', NULL),('support', 'integer', '支持数', '0', '支持数', 'input', '', '', 0, 0, 0, 0, {$entityId}, 10, '', '2020-01-14 09:45:04', '2020-01-14 09:53:31', NULL),('comment', 'integer', '评论数', '0', '评论数', 'input', '', '', 0, 0, 0, 0, {$entityId}, 11, '0', '2020-01-14 09:45:35', '2020-01-14 09:53:42', NULL),('collect', 'integer', '收藏数', '0', '收藏数', 'input', '', '', 0, 0, 0, 0, {$entityId}, 12, '0', '2020-01-14 09:46:04', '2020-01-14 09:53:54', NULL),('sort', 'integer', '排序 由大到小', '10', '排序 由大到小', 'input', '', '', 1, 0, 1, 1, {$entityId}, 13, '0', '2020-01-14 09:46:56', '2020-01-14 09:46:56', NULL),('status', 'tinyInteger', '状态', '0', '状态', 'option', '', '-1=下架\n0=未发布\n1=1级审核通过\n2=2级审核通过\n99=发布', 1, 0, 1, 1, {$entityId}, 14, '0', '2020-01-14 09:48:26', '2020-01-14 09:48:26', NULL),('audit', 'tinyInteger', '是否需要审核 0:不需要审核; 1:需要1级审核; 2:需要2级审核', '0', '是否需要审核', 'option', '', '0=不需要审核\n1=需要1级审核\n2=需要2级审核', 1, 0, 1, 1, {$entityId}, 15, '0', '2020-01-14 09:49:35', '2020-01-14 09:49:35', NULL),('fixed_release_time', 'timestamp', '定时发布时间', '', '定时发布时间', 'datetime', '', '', 1, 0, 1, 1, {$entityId}, 16, '', '2020-01-14 09:50:14', '2020-01-14 09:50:14', NULL),('extend', 'json', '扩展字段', '', '扩展字段', 'textArea', '', '', 0, 0, 0, 0, {$entityId}, 17, '', '2020-01-14 09:51:21', '2020-01-14 09:54:54', NULL),('admin_user_id', 'integer', '创建人编号', '0', '创建人编号', 'reference_admin_user', '', '', 1, 0, 1, 1, {$entityId}, 18, '0', '2020-01-14 09:51:47', '2020-01-14 09:51:47', NULL);";
         DB::unprepared($sql);*/
    }
}
